import type {
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
  ScopeContext,
} from '@fast-crud/fast-crud';
import type { Dayjs } from 'dayjs';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { useAccess } from '@vben/access';
import { $t } from '@vben/locales';

import { dict } from '@fast-crud/fast-crud';
import { Tag } from 'ant-design-vue';

import { DefApplicationApi, DefTenantApi } from '#/api';
import { DefTenantApplicationRelApi } from '#/api/devOperation/application/defTenantApplicationRel';
import { RouteEnum } from '#/enums/commonEnum';
import { PermCode } from '#/enums/perm';
import { useMessage } from '#/hooks/web/useMessage';
import { createdTimeColumn, indexColumn } from '#/plugins/fast-crud/common';
import { dateUtil } from '#/utils/dateUtil';

const { hasPermission } = useAccess();
const permCode = PermCode.devOperation.application.defTenantApplicationRel;

export function createCrudOptions(
  props: CreateCrudOptionsProps,
): CreateCrudOptionsRet {
  const selectedRowKeys = ref<string[]>([]);
  const { push } = useRouter();
  const { createMessage, createConfirm } = useMessage();
  return {
    crudOptions: {
      request: {
        pageRequest: DefTenantApplicationRelApi.pageRequest,
        editRequest: DefTenantApplicationRelApi.editRequest,
        infoRequest: DefTenantApplicationRelApi.infoRequest,
      },
      form: {
        wrapper: {
          is: 'a-drawer',
          width: '50%',
          draggable: false,
        },
        col: { span: 24 },
      },
      actionbar: {
        buttons: {
          add: { show: false },
          authorizeGrant: {
            show: hasPermission(permCode.grant),
            text: '批量授权',
            type: 'primary',
            click() {
              push({ name: RouteEnum.APPLICATION_GRANT });
            },
          },
          batchCancel: {
            show: hasPermission(permCode.cancel),
            text: '取消授权',
            danger: true,
            click() {
              if (selectedRowKeys.value?.length > 0) {
                createConfirm({
                  iconType: 'warning',
                  content: `确定要批量取消授权这${selectedRowKeys.value.length}条记录吗`,
                  onOk: async () => {
                    const flag = await DefTenantApplicationRelApi.cancel(
                      selectedRowKeys.value,
                    );
                    if (flag) {
                      createMessage.info('操作成功');

                      selectedRowKeys.value = [];
                      await props.crudExpose?.doRefresh();
                    }
                  },
                });
              } else {
                createMessage.warning('请先勾选您要取消的数据');
              }
            },
          },
        },
      },
      table: {
        striped: true,
        rowKey: 'id',
        rowSelection: {
          type: 'checkbox',
          selectedRowKeys,
          onChange: (changed: string[]) => {
            selectedRowKeys.value = changed;
          },
        },
      },
      rowHandle: {
        width: 150,
        buttons: {
          edit: { show: hasPermission(permCode.renewal) },
          view: { show: false },
          remove: { show: false },
          copy: { show: false },
          cancel: {
            show: hasPermission(permCode.cancel),
            text: '取消授权',
            type: 'link',
            size: 'small',
            order: 10,
            async click({ row }) {
              createConfirm({
                iconType: 'warning',
                content: `确定要取消授权这条记录吗`,
                onOk: async () => {
                  await DefTenantApplicationRelApi.cancel([row.id]);
                  createMessage.success('取消成功');
                  await props.crudExpose?.doRefresh();
                },
              });
            },
          },
        },
      },
      columns: {
        ...indexColumn(props.crudExpose),
        tenantId: {
          title: $t(
            'devOperation.application.defTenantApplicationRel.tenantId',
          ),
          type: 'dict-select',
          dict: dict({
            value: 'id',
            label: 'name',
            async getData() {
              return await DefTenantApi.query({});
            },
          }),
          editForm: { component: { disabled: true } },
          search: { show: true },
          column: {
            component: {
              type: 'text',
            },
          },
        },
        applicationId: {
          title: $t(
            'devOperation.application.defTenantApplicationRel.applicationId',
          ),
          type: 'dict-select',
          dict: dict({
            value: 'id',
            label: 'name',
            async getData() {
              return await DefApplicationApi.query({});
            },
          }),
          editForm: { component: { disabled: true } },
          search: { show: true },
          column: {
            component: {
              type: 'text',
            },
          },
        },
        expirationTime: {
          title: $t(
            'devOperation.application.defTenantApplicationRel.expirationTime',
          ),
          type: 'datetime',
          form: {
            component: {
              format: 'YYYY-MM-DD HH:mm:ss',
              valueFormat: 'YYYY-MM-DD HH:mm:ss',
              'disabled-date': (current: Dayjs): boolean => {
                return current < dateUtil().endOf('day');
              },
            },
          },
          valueBuilder({ value, row, key }) {
            if (value !== null) {
              row[key] = value;
            }
          },
          column: {
            width: 180,
            formatter: (context: ScopeContext) => {
              const record = context.row;
              if (record.expirationTime) {
                if (dateUtil(record.expirationTime).isBefore(Date.now())) {
                  return <Tag color="error">已过期</Tag>;
                } else if (
                  dateUtil(record.expirationTime).isBefore(
                    dateUtil().add(30, 'days'),
                  )
                ) {
                  const duration = dateUtil.duration(
                    dateUtil(record.expirationTime).diff(Date.now()),
                  );
                  if (duration.days() > 0) {
                    return (
                      <Tag color="warning">{duration.days() + 1}天后到期</Tag>
                    );
                  }
                  return (
                    <Tag color="warning">{duration.hours()}小时后到期</Tag>
                  );
                }
                return <Tag color="processing">{record.expirationTime}</Tag>;
              }
              return <Tag color="success">永久有效</Tag>;
            },
          },
        },
        resourceIdList: {
          title: '资源',
          type: 'text',
          column: { show: false },
          form: {},
          valueResolve({ form, key }) {
            if (form && form[key]) {
              form[key] = form[key]?.checked;
            }
          },
        },
        ...createdTimeColumn({}),
      },
    },
  };
}
